package com.yixun.qfbao.hander;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.yixun.common.page.Page;
import com.yixun.qfbao.api.service.CompanyRelationService;
import com.yixun.qfbao.apidto.AgentCompanyRegesitResDto;
import com.yixun.qfbao.apidto.GetAgentCompanyRegesitListResDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.model.CheckRecord;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.CompanyRelation;
import com.yixun.qfbao.model.ModelInfo;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.dto.CheckRecordDto;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.CompanyRelationDto;
import com.yixun.qfbao.model.enums.CreateOriginEnum;
import com.yixun.qfbao.model.enums.ModelTypeEnum2;
import com.yixun.qfbao.service.CheckRecordService;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.ModelInfoService;
import com.yixun.qfbao.util.StringUtil;
import com.yixun.qfbao.utils.LoginUtils;
import com.yixun.qfbao.vo.GetAgentCompanyRegesitListReqVo;
import com.yixun.qfbao.xf.model.enums.ResultEnum;

/**
 * @author zilong.liu
 * @date 2020-12-16
 *
 * desc:
 *     	获取公司注册列表
 */
@Service("getAgentCompanyRegesitListHander")
public class GetAgentCompanyRegesitListHander extends CommonAbstractHander{

	@Autowired
	LoginUtils loginUtils;
	
	@Autowired
	CompanyRelationService companyRelationService;
	
	@Autowired
	CompanyService companyService;
	
	@Autowired
	ModelInfoService modelInfoService;
	
	@Autowired
	CheckRecordService checkRecordService;
	
	@Override
	@SuppressWarnings({ "rawtypes"})
	public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
		BaseResponseDTO<GetAgentCompanyRegesitListResDto> res = new BaseResponseDTO<>();
		GetAgentCompanyRegesitListResDto getAgentCompanyRegesitListResDto = new GetAgentCompanyRegesitListResDto();
		
		GetAgentCompanyRegesitListReqVo reqVo = (GetAgentCompanyRegesitListReqVo) reqDto;
		String userId = reqVo.getParams().getUserId();
		PartnerInfo partnerInfo = loginUtils.getUser(userId);
		if(partnerInfo == null) {
			res.setResult(ResultEnum.FAIL.getNo());
            res.setErrorMsg("未找到用户信息");
            return res;
		}
		
		// 获取当前总代下的所有合作公司ID，然后再查询不包括不需要审核的列表
		CompanyRelationDto entity = new CompanyRelationDto();
		entity.setDevCompany(partnerInfo.getHigherid());
		List<CompanyRelation> companyRelationList = companyRelationService.selectListByDto(entity);
		if(CollectionUtils.isEmpty(companyRelationList)) {
			res.setResData(getAgentCompanyRegesitListResDto);
			getAgentCompanyRegesitListResDto.setCompanyId(partnerInfo.getHigherid());
			res.setResult(ResultEnum.SUCCESS.getNo());
			return res;
		}

		List<Long> ids = new ArrayList<>(companyRelationList.size());
		companyRelationList.stream().forEach(companyRelation -> {
			ids.add(companyRelation.getAgentCompany());
		});
		
		
		CompanyDto companyDto = new CompanyDto(); 
		String condition = reqVo.getParams().getCondition();
		String checkStatus = reqVo.getParams().getCheckStatus();
		
		int pageNo = reqVo.getParams().getPageNo();
		int pageSize = reqVo.getParams().getPageSize();
		
		if(StringUtil.isNotNull(condition)) {
			companyDto.setSql(" AND (t.charge_man like '%" + condition + "%' OR"
					+ " t.phone like '%" + condition + "%')");
		}
		
		if(StringUtil.isNotNull(checkStatus)) {
			companyDto.setStatus(checkStatus);
		}else {
			companyDto.setStatusNotFilterFlag(true);
		}
		companyDto.setCreateOrigin(CreateOriginEnum.WEAPP_REGESIT.getCode());
		companyDto.setIds(ids);
		companyDto.setOrders("t.id desc");
		
		// 分页查找公司的集合
		Page<Company> companyPage = companyService.getPageModel(companyDto, (pageNo - 1) * pageSize, pageSize);
		companyPage.setPageSize(pageSize);
		List<Company> companyList = companyPage.getRows();
		
		List<AgentCompanyRegesitResDto> companyRegesitDtoList = new ArrayList<>(companyList.size());
		Page<AgentCompanyRegesitResDto> companyRegesitDtoPage = new Page<>(companyPage.getTotal(), companyRegesitDtoList);
		companyRegesitDtoPage.setTotalPages(companyPage.getTotalPages());
		if(!CollectionUtils.isEmpty(companyList)) {
			List<Long> idList = new ArrayList<>(companyList.size());
			
			companyList.forEach(company -> {
				idList.add(company.getId());
				
			});
			
			CheckRecordDto checkRecordDto = new CheckRecordDto();
			checkRecordDto.setType(ModelTypeEnum2.COMPANY.getNo());
			checkRecordDto.setRelIds(ids);
			List<CheckRecord> checkRecordList = checkRecordService.selectByDto(checkRecordDto);
			
			ModelInfo modelInfo = new ModelInfo();
			modelInfo.setRelIdList(idList);
			modelInfo.setModelType(ModelTypeEnum2.COMPANY.getNo());
			List<ModelInfo> modelInfoList = modelInfoService.selectListByDto(modelInfo);
			companyList.forEach(company -> {
				AgentCompanyRegesitResDto agentCompanyRegesitResDto = AgentCompanyRegesitResDto.converCompanyToThis(company);
				if(company.getCreateTime() != null) {
					String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(company.getCreateTime());
					agentCompanyRegesitResDto.setCreateTime(createTime);
				}
				if(!CollectionUtils.isEmpty(checkRecordList)) {
					// 把remark 放到对应的记录中并返回
					checkRecordList.forEach(checkRecord -> {
						if(checkRecord.getRelId().longValue() == agentCompanyRegesitResDto.getId().longValue()) {
							String remark = StringUtil.isNotNull(checkRecord.getRemark())? checkRecord.getRemark(): "";
							agentCompanyRegesitResDto.setRemark(remark);
						}
					});
				}
				if(!CollectionUtils.isEmpty(modelInfoList)) {
					// 把模板信息放入到对应的ID审核记录中
					modelInfoList.forEach(eachModelInfo -> {
						agentCompanyRegesitResDto.addModelInfoResDto(eachModelInfo);
					});
				}
				companyRegesitDtoList.add(agentCompanyRegesitResDto);
			});
		}
		companyRegesitDtoPage.setRows(companyRegesitDtoList);
		getAgentCompanyRegesitListResDto.setAgentCompanyRegesitPage(companyRegesitDtoPage);
		
		res.setResData(getAgentCompanyRegesitListResDto);
		getAgentCompanyRegesitListResDto.setCompanyId(partnerInfo.getHigherid());
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	

}
